﻿// handle communication between library components
angular.module('app.user').service('libraryMediator', ['uploadService', 'dataService',
	function (uploadService, dataService) {
		'use strict';

		var svc = {
			imageContainerController: {},
			uploadController: {},
			folderController: {},
			// sets the image container controller reference
			setImageContainerController: function (controller) {
				svc.imageContainerController = controller;
			},
			// sets the upload controller reference
			setUploadController: function (controller) {
				svc.uploadController = controller;
			},
			// sets the folder controller reference
			setFolderController: function (controller) {
				svc.folderController = controller;
			},
			// submit the rename for a folder through the upload service
			renameFolder: function (folder) {
				dataService.upload('Folder', { Id: folder.Id, Name: folder.newName })
					.then(svc.folderController.handleRenameFolderResponse);
			},
			// uploads an image
			upload: function (formData, folderId) {
				// upload the image
				return uploadService.upload(formData, folderId).then(function (reply) {
					// when the image had been uploaded, notify the image container controller
					if (svc.imageContainerController.handleImageUploaded !== undefined) {
						svc.imageContainerController.handleImageUploaded(reply.data);
					}
					// when the image has been uploaded, notify the upload controller.
					if (svc.uploadController.handleImageUploaded !== undefined) {
						svc.uploadController.handleImageUploaded(reply.data);
					}
				});
			}
		};

		return svc;
	}]);